import { Component, OnInit } from '@angular/core'
import { Location } from '@angular/common'
import { Router } from '@angular/router'
import { ChangeDetectorRef } from '@angular/core'
import { CommonUtil } from 'src/app/common/utils/common.util'
import { HttpClientService } from 'src/app/common/httpClient/http'
import { CoolLocalStorage } from 'src/app/common/coolStorage/cool-local-storage'
import { CoolSessionStorage } from 'src/app/common/coolStorage/cool-session-storage'

@Component({
  selector: 'app-select-city',
  templateUrl: './select-city.component.html',
  styleUrls: ['./select-city.component.scss']
})
export class SelectCityComponent implements OnInit {
  // 定位城市
  city = {
    Id: '',
    Name: ''
  }
  // 最近访问城市
  recentCity = []
  // 城市列表
  cityList = []
  error = false
  loading = false
  // 字母组
  searchLetter = [
    'A',
    'B',
    'C',
    'D',
    'E',
    'F',
    'G',
    'H',
    'J',
    'K',
    'L',
    'M',
    'N',
    'P',
    'Q',
    'R',
    'S',
    'T',
    'W',
    'X',
    'Y',
    'Z'
  ]
  // 定位城市是否开通
  disabled = false
  // 定位失败
  geoErr = false
  // 定位中
  geoing = false

  constructor(
    private location: Location,
    private router: Router,
    private utils: CommonUtil,
    private http: HttpClientService,
    private storage: CoolLocalStorage,
    private session: CoolSessionStorage,
    public changeDetectorRef: ChangeDetectorRef
  ) {}

  // 初始化
  ngOnInit() {
    this.loading = true
    let platformId = this.storage.getItem('platformId')
    if (platformId) {
      this.getCurrentPosition()
    }
    this.getRecentCity()
    this.getCityList()
  }
  // 返回
  onClickLeft() {
    this.location.back()
  }
  // 获取当前位置
  getCurrentPosition() {
    console.log('正在定位...')
    this.geoErr = false
    this.geoing = true
    navigator.geolocation.getCurrentPosition(
      position => {
        this.onSuccess(position)
      },
      error => {
        this.onError(error)
      }
    )
  }
  // 定位成功
  onSuccess(position) {
    console.log(position)
    this.transformPositon(
      position.coords.latitude,
      position.coords.longitude,
      res => {
        console.log('经纬度转换成功')
        this.reverAddress(
          res.locations[0].lat,
          res.locations[0].lng,
          data => {
            console.log('城市转换成功：' + data.result.ad_info.city)
            this.geoErr = false
            this.geoing = false
            let city = data.result.ad_info.city
            let lat = data.result.location.lat
            let lng = data.result.location.lng
            let location = { latitude: lat, longitude: lng, city: city }
            this.city = this.matchCity(city)
            this.storage.setObject('location', location)
            this.changeDetectorRef.markForCheck()
            this.changeDetectorRef.detectChanges()
          },
          () => {
            console.log('城市转换失败')
            this.handleFail()
          }
        )
      },
      () => {
        console.log('经纬度转换失败')
        this.handleFail()
      }
    )
  }
  // 定位失败
  onError(error) {
    this.handleFail()
  }
  // 经纬度转换
  transformPositon(lat, lng, callback, errBack?) {
    this.http.get(
      `https://apis.map.qq.com/ws/coord/v1/translate?locations=${lat},${lng}&type=1&key=KPJBZ-TIR6R-YTPWI-WER7Z-QP3J3-KIBI3`,
      callback,
      errBack
    )
  }
  // 逆地址解析
  reverAddress(lat, lng, callback, errBack?) {
    this.http.get(
      `https://apis.map.qq.com/ws/geocoder/v1/?location=${lat},${lng}&key=KPJBZ-TIR6R-YTPWI-WER7Z-QP3J3-KIBI3`,
      callback,
      errBack
    )
  }
  // 获取最近城市
  getRecentCity() {
    let recentCity: any = this.storage.getObject('recentCity')
    if (recentCity && recentCity.length > 0) {
      this.recentCity = recentCity
    }
  }
  // 更新最近城市的本地存储记录
  updateRecentCity(Id, Name) {
    let index: number
    let recentCity: any = this.storage.getObject('recentCity')
    if (!Id || !Name) {
      return false
    }
    // 如果本地存储有最近城市，那么把新的记录插入
    // 如果本地存储没有最近城市，那么直接插入一条
    if (recentCity && recentCity.length > 0) {
      for (let i = 0; i < recentCity.length; i++) {
        if (Id === recentCity[i].Id) {
          index = i
        }
      }
      // 如果插入的已存在，那么把这条记录放在最前面
      if (index > -1) {
        recentCity.splice(index, 1)
      }
      recentCity.unshift({ Id: Id, Name: Name })
    } else {
      recentCity = [{ Id: Id, Name: Name }]
    }
    this.storage.setObject('recentCity', recentCity)
  }
  // 获取城市列表
  getCityList() {
    let cityList: any = this.storage.getObject('cityList')
    if (cityList && cityList.length > 0) {
      this.cityList = this.disposeCity(cityList)
    }
    this.loading = false
  }
  // 城市按字母排序
  disposeCity(cities) {
    let searchLetter = this.searchLetter
    let cityList = []

    for (let i = 0; i < searchLetter.length; i++) {
      let Initial = searchLetter[i]
      let CityInfo = []
      let tempArr = {}
      tempArr['Initial'] = Initial

      for (let j = 0; j < cities.length; j++) {
        let item = cities[j]
        let letter = (item.CityInfo && item.CityInfo.Pinyin2 && item.CityInfo.Pinyin2.substring(0, 1)) || ''
        if (Initial == letter) {
          let ob = { Id: item.Id, Name: item.Name, Initial: letter }
          CityInfo.push(ob)
        }
      }
      if (CityInfo.length > 0) {
        tempArr['CityInfo'] = CityInfo
        cityList.push(tempArr)
      }
    }
    return cityList
  }
  // 根据城市名称在城市列表中匹配
  matchCity(cityName) {
    let city: any
    let flag = false
    let cityList: any = this.storage.getObject('cityList')
    if (cityList.length === 0) {
      return false
    }
    for (let i = 0; i < cityList.length; i++) {
      if (cityName.indexOf(cityList[i].Name) > -1) {
        flag = true
        city = { Id: cityList[i].Id, Name: cityList[i].Name }
      }
    }
    if (flag) {
      this.disabled = false
    } else {
      this.disabled = true
      city = { Id: null, Name: cityName }
    }

    return city
  }
  // 选择城市
  selectCity(item) {
    console.log(item)
    if (!item.Id) {
      this.utils.info('当前城市暂未开通服务')
      return false
    }
    this.updateRecentCity(item.Id, item.Name)
    this.session.removeItem('noticeShowTime')
    this.router.navigate(['/workspace/home/index', { Id: item.Id, Name: item.Name }])
  }
  // 失败统一处理
  handleFail() {
    this.geoErr = true
    this.geoing = false
    this.utils.info('定位失败，请手动选择城市')
  }
}
